import backtrader as bt


# backtrader识别量价异动
class VolumePriceAnomaly(bt.Strategy):
    def __init__(self):
        self.volume_change = bt.indicators.RateOfChange(self.data.volume, period=1)
        self.price_change = bt.indicators.RateOfChange(self.data.close, period=1)

    def next(self):
        volume_change = self.volume_change[0]
        price_change = self.price_change[0]

        # 定义量价异动的阈值，您可以根据实际情况调整
        volume_threshold = 0.5
        price_threshold = 0.3

        if (
            abs(volume_change) > volume_threshold
            and abs(price_change) > price_threshold
        ):
            print(
                f"量价异动: 成交量变化率 {volume_change:.2f}, 价格变化率 {price_change:.2f}"
            )


# 示例使用
cerebro = bt.Cerebro()
data = bt.feeds.YahooFinanceData(
    dataname="AAPL", fromdate=datetime(2020, 1, 1), todate=datetime(2024, 1, 1)
)
cerebro.adddata(data)
cerebro.addstrategy(VolumePriceAnomaly)
cerebro.run()
